﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO.Ports;

namespace iPublic
{
    /// <summary>
    /// 串口支持，海宏软件
    /// 修改记录：
    ///   20171214，zch，创建空单元
    /// </summary>
    public partial class iComHelper
    {

        /// <summary>
        /// 公共串口组件
        /// </summary>
        public static System.IO.Ports.SerialPort comPort = null;


        public iDefine.ChuLiJieGuo 打开拍照led灯() { return write("A"); }
        public iDefine.ChuLiJieGuo 关闭拍照led灯() { return write("B"); }
        public iDefine.ChuLiJieGuo 打开出物口led灯() { return write("C"); }
        public iDefine.ChuLiJieGuo 关闭出物口led灯() { return write("D"); }
        public iDefine.ChuLiJieGuo 打开所有led灯() { return write("E"); }
        public iDefine.ChuLiJieGuo 关闭所有led灯() { return write("F"); }
        public iDefine.ChuLiJieGuo 电机左转储物箱() { return write("Z"); }
        public iDefine.ChuLiJieGuo 电机右转取回口() { return write("Y"); }
        //public iDefine.ChuLiJieGuo 电机转到90度停止位() { return write("T"); }    //此指令已废弃，自动回位
        /// <summary>
        /// 上前门是维修用的
        /// </summary>
        /// <returns></returns>
        public iDefine.ChuLiJieGuo 开上前门锁() { return write("W"); }
        /// <summary>
        /// 下前门是取回收物用的
        /// </summary>
        /// <returns></returns>
        public iDefine.ChuLiJieGuo 开下前门锁() { return write("V"); }

        public iDefine.ChuLiJieGuo write(string str)
        {
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo(), jg = null;
            byte[] buf = System.Text.Encoding.Default.GetBytes(str);
            //下边这个地方很奇怪，C#发出去的字符串，总是莫名其妙的超出F3就乱码，于是转成Unicode，但是Unicode每个字节前多一个00字节，这样移除
            //byte[] db2 = Encoding.Unicode.GetBytes(buf.ToString()), db = new byte[db2.Length / 2];
            //for (int i = 0; i < db2.Length; i++) if ((i % 2) == 0) db[i / 2] = db2[i];
            //return write(buf);
            string s = "";
            try
            {
                //日志
                s = " 写串口" + iDefine.SysConfig.sComPort + "：" + str;
                iLog.writeLogFile(s);
                //输出
                jg = openPort();                        //打开串口
                if (jg.error != 0) throw new Exception("打开串口错误：" + jg.error.ToString() + "," + jg.message);
                comPort.Write(str);
                System.Threading.Thread.Sleep(20);      //等10毫秒
                //完成
                result.error = 0;
                result.message = "ok";
            }
            catch (Exception x)
            {
                result.message = x.Message;
                if (result.error <= 0) result.error = 100;
            }
            return result;
        }
        public iDefine.ChuLiJieGuo write(byte[] buf)
        {
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo(), jg = null;
            string s = "";
            try
            {
                //日志
                s = " 写串口" + iDefine.SysConfig.sComPort + "：" + System.Text.Encoding.Default.GetString(buf);
                iLog.writeLogFile(s);
                //输出
                jg = openPort();                        //打开串口
                if (jg.error != 0) throw new Exception("打开串口错误：" + jg.error.ToString() + "," + jg.message);
                comPort.Write(buf, 0, buf.Length);
                System.Threading.Thread.Sleep(10);      //等10毫秒
                //完成
                result.error = 0;
                result.message = "ok";
            }
            catch (Exception x)
            {
                result.message = x.Message;
                if (result.error <= 0) result.error = 100;
            }
            return result;
        }

        #region //openPort，打开串口
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <returns>处理结果</returns>
        public iDefine.ChuLiJieGuo openPort()
        {
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo();
            try
            {
                createPort();
                //打开串口
                iLog.writeLogFile("打开串口" + iDefine.SysConfig.sComPort + "," + iDefine.SysConfig.nComBaudRate.ToString());
                if (comPort != null && !comPort.IsOpen) comPort.Open();
                //完成
                result.error = 0;
                result.message = "ok," + iDefine.SysConfig.sComPort + "," + iDefine.SysConfig.nComBaudRate.ToString();
            }
            catch (Exception x)
            {
                if (result.error <= 0) result.error = 100;
                result.message = x.Message;
            }
            return result;
        }
        #endregion


        #region //createPort，创建串口
        private static void createPort(bool lRaisError=true)
        {   //创建串口
            if (comPort != null) return;
            //创建串口组件
            if (string.IsNullOrEmpty(iDefine.SysConfig.sComPort))
            {
                if (lRaisError) throw new Exception("未设置串口号，请从app.config设置串口号"); else return;
            }
            comPort = new System.IO.Ports.SerialPort(iDefine.SysConfig.sComPort, iDefine.SysConfig.nComBaudRate);
            comPort.NewLine = "\n";                 //c#默认在发完的数据后加了\r\n0A0D回车换行
        }
        #endregion


        #region //closePort关闭串口
        public int closePort()
        {   //关闭串口
            if (comPort == null) return 0;
            comPort.Close();
            comPort.Dispose();
            comPort = null;
            return 0;
        }
        #endregion


        public bool isPortReady
        {
            get
            {
                createPort(false);
                return comPort != null;
            }
        }


        public iComHelper()
        {   //初始化
            if (comPort == null && !string.IsNullOrEmpty(iDefine.SysConfig.sComPort)) createPort();
        }

        ~iComHelper()
        {   //释放串口
            closePort();
        }

    }

}
